﻿import {ScreenMgr, System} from "csharp";
import {$typeof} from "puerts";

export class ServiceLocator{
    static services = new Map();
    public static Get<T extends any|System.Object>(compType:{new(...arg:any[]):T}):T
    {
        if(compType.prototype instanceof System.Object){
            let cmp = ScreenMgr.ServiceLocator.Get($typeof(compType))
            if(cmp === null)
                return null;
            return cmp as T;
        }
        return this.services.get(compType)
    }

    //  注册指定的服务实例。通常在Awake（）中调用
    public static Register<T extends any|System.Object>(typeT: {new(...arg:any[]):T},service:any,overwrite:boolean)
    {
        if(service.prototype instanceof System.Object){
            let cmp = ScreenMgr.ServiceLocator.Register(service,overwrite)
            if(cmp === null)
                return null;
            return cmp as T;
        }
        if(!overwrite && this.services.has(typeT)) {
            throw new Error("Duplicate " + typeof(typeT));
        }
        this.services.set(typeT,service);
    }
    //  解除注册指定的服务类型实例。
    public static Unregister<T extends any|System.Object>(compType:{new(...arg:any[]):T}) 
    {
        if(compType.prototype instanceof System.Object){
            ScreenMgr.ServiceLocator.Unregister($typeof(compType))
        }
        return this.services.delete(compType)
    }
    
    public static  Clear(){
        ScreenMgr.ServiceLocator.Clear()
        this.services.clear()
    }
}